package org.elepower.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.elepower.dao.*;
import org.elepower.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/solveTaskMain")
public class SolveTaskMainController {
    @Autowired
    private SolveMainDao solveMainDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private SystemConfigDao systemConfigDao;
    @Autowired
    private SolverDao solverDao;
    @Autowired
    private InspectiontaskDetailsDao inspectiontaskDetailsDao;
    @Autowired
    private SolveDetailDao solveDetailDao;

    @RequestMapping("/index")
    public String index() throws Exception{
        return "system/solve/index";
    }

    @RequestMapping("/getList")
    @ResponseBody
    public Map<String, Object> getList(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer limit, PsSolvetaskMain condition, HttpServletRequest request) throws Exception {

        Map<String, Object> map = new HashMap<>();

        Page<PsInspectiontask_main> pager = PageHelper.startPage(page, limit);
        List<PsSolvetaskMain> list = solveMainDao.getlist(condition);
        request.setAttribute("list",list);
        map.put("code", 0);
        map.put("msg", "");
        map.put("data", list);
        map.put("count", pager.getTotal());
        return map;
    }

    @RequestMapping("/form")
    public String form() throws Exception{
        return "system/solve/form";
    }

    /**
     * 根据消缺员编号字符串分割数组
     * @param solvers
     * @return
     */
    public Integer[] needInspectorIds(String[] solvers){
        Integer[] solverIds = new Integer[solvers.length];
        if(solvers != null && solvers.length != 0){
            for(int i = 0; i < solvers.length;i++){
                solverIds[i] = Integer.parseInt(solvers[i]);
            }
        }
        return solverIds;
    }

    @RequestMapping(value = "add",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> add(PsSolvetaskMain psSolvetaskMain, @RequestParam("solverStr") String solverStr, HttpSession session, @RequestParam("datetime") String datetime,@RequestParam("bugIdStr") String bugIdStr,@RequestParam("taskManagerId")String taskManagerId) throws Exception{
        Map<String, Object> map = new HashMap<>();

        //消缺员编号
        String[] solvers = solverStr.split(",");
        Integer[] solverIds = new Integer[]{};
        if(!solverStr.equals("") && solverStr != null){
            solverIds = needInspectorIds(solvers);
        }
        //其他信息
        PsUser psUser = (PsUser)session.getAttribute(Constants.LOGIN_USER);

        psSolvetaskMain.setCreatedBy(psUser.getUsername());

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        psSolvetaskMain.setIssuedTime(format.parse(datetime));
        //判断任务状态
        if(!solverStr.equals("") && solverStr != null){
            psSolvetaskMain.setTaskStateId(2);
            psSolvetaskMain.setTaskStateName("已分配");
        }else{
            psSolvetaskMain.setTaskStateId(1);
            psSolvetaskMain.setTaskStateName("待分配");
        }
        psSolvetaskMain.setIsCancel(0);
        //查询工作单据
        PsSysteamconfig danju = systemConfigDao.getDanJuId(psSolvetaskMain.getWorkDocTypeId());
        psSolvetaskMain.setWorkDocTypeName(danju.getConfigValueName());
        //查询负责人信息
        PsUser user = userDao.getUser(Integer.parseInt(taskManagerId));
        psSolvetaskMain.setTaskManagerId(Integer.parseInt(taskManagerId));
        psSolvetaskMain.setTaskManagerCode(user.getName());
        psSolvetaskMain.setTaskManagerName(user.getUsername());
        System.out.println(psSolvetaskMain.getSolvers());
        //添加消缺任务
        solveMainDao.add(psSolvetaskMain);
        if(!solverStr.equals("")){
            //添加消缺员任务
            solverDao.updateSolverTask(solverIds,psSolvetaskMain.getId());
        }
        //添加消缺任务字表
        String[] bugs = bugIdStr.split(",");
        PsSolvetaskDetail psSolvetaskDetail = new PsSolvetaskDetail();//消缺任务字表
        psSolvetaskDetail.setCreatedBy(psUser.getUsername());
        psSolvetaskDetail.setTaskId(psSolvetaskMain.getId());
        for (int i = 0;i < bugs.length;i++){
            psSolvetaskDetail.setInspectionTaskDelId(Integer.parseInt(bugs[i]));
            //添加消缺子表任务
            solveDetailDao.add(psSolvetaskDetail);
        }

        map.put("result",true);
        return map;
    }

    @RequestMapping("/getLineUser")
    @ResponseBody
    public List<PsUser> getLineUser() throws Exception{
        return userDao.getLineUser();
    }

    @RequestMapping("/getDanJu")
    @ResponseBody
    public List<PsSysteamconfig> getDanJu() throws Exception{
        return systemConfigDao.getDanJu();
    }

    @RequestMapping("/getBug")
    @ResponseBody
    public Map<String, Object> list(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer limit) throws Exception {

        Map<String, Object> map = new HashMap<>();

        List<PsInspectiontaskDetails> list = inspectiontaskDetailsDao.solveBug();
        map.put("code", 0);
        map.put("msg", "");
        map.put("data", list);
        map.put("count", 0);
        return map;
    }

    @RequestMapping("/selectSolveTask")
    public String selectSolveTask(Integer taskId,HttpSession session) throws Exception{
        session.setAttribute("solveTaskId",taskId);
        return "system/solve/solveSelect";
    }

    @RequestMapping("/getSolveTask")
    @ResponseBody
    public Map<String, Object> getSolveTask(HttpSession session) throws Exception {

        Map<String, Object> map = new HashMap<>();
        Integer taskId = (Integer)session.getAttribute("solveTaskId");
        System.out.println(taskId);
        //根据任务编号查询缺陷编号
        List<PsSolvetaskDetail> solverDetailList = solveDetailDao.getBugForTaskId(taskId);
        //缺陷任务编号
        Integer[] ids = new Integer[solverDetailList.size()];
        int i = 0;
        for (PsSolvetaskDetail solver:
             solverDetailList) {
            ids[i] = solver.getInspectionTaskDelId();
            System.out.println(solver.getId());
        }
        List<PsInspectiontaskDetails> list = new ArrayList<>();
        //判断是否有缺陷
        if(ids != null && ids.length != 0){
            list = inspectiontaskDetailsDao.getInspectionForId(ids);
        }
        map.put("code", 0);
        map.put("msg", "");
        map.put("data", list);
        map.put("count", 0);
        return map;
    }

    @RequestMapping("/getTask")
    @ResponseBody
    public PsSolvetaskMain getTask(Integer taskId) throws Exception{
        return solveMainDao.get(taskId);
    }

    @RequestMapping("/addSolverTask")
    @ResponseBody
    public Map<String,Object> addSolver(@RequestParam("taskId") Integer taskId,@RequestParam("solverStr") String solverStr,@RequestParam("solvers")String solverString) throws Exception{
        Map<String,Object> map = new HashMap<>();
        //消缺员编号
        String[] solvers = solverStr.split(",");
        Integer[] solverIds = new Integer[]{};
        if(!solverStr.equals("") && solverStr != null){
            solverIds = needInspectorIds(solvers);
        }
        //添加消缺员信息
        if(!solverStr.equals("")){
            //添加消缺员任务
            solverDao.updateSolverTask(solverIds,taskId);
        }
        //修改消缺任务状态
        solveMainDao.updateSolveState(2,"已分配",taskId);
        //修改消缺任务消缺员列
        solveMainDao.updateTaskSolvers(taskId,solverString);
        map.put("result",true);
        return map;
    }

    @RequestMapping("/cancel")
    @ResponseBody
    public Map<String,Object> cancel(Integer taskId) throws Exception{
        Map<String,Object> map = new HashMap<>();
        //修改任务状态
        solveMainDao.updateTaskState(taskId);
        //修改消缺员状态
        solverDao.updateTaskIdSolverState(taskId);
        map.put("result",true);
        //删除消缺任务字表信息
        solveDetailDao.deleteForTaskId(taskId);
        return map;
    }

    @RequestMapping("/update")
    @ResponseBody
    public Map<String,Object> update(PsSolvetaskMain psSolvetaskMain, @RequestParam("solverStr") String solverStr, HttpSession session,@RequestParam("taskManagerId")String taskManagerId) throws Exception{
        Map<String,Object> map = new HashMap<>();
        //消缺员编号
        String[] solvers = solverStr.split(",");
        Integer[] solverIds = new Integer[]{};
        if(!solverStr.equals("") && solverStr != null){
            solverIds = needInspectorIds(solvers);
        }
        //判断任务状态
        if(!solverStr.equals("") && solverStr != null){
            psSolvetaskMain.setTaskStateId(2);
            psSolvetaskMain.setTaskStateName("已分配");
        }else{
            psSolvetaskMain.setTaskStateId(1);
            psSolvetaskMain.setTaskStateName("待分配");
        }
        psSolvetaskMain.setIsCancel(0);
        //查询工作单据
        PsSysteamconfig danju = systemConfigDao.getDanJuId(psSolvetaskMain.getWorkDocTypeId());
        psSolvetaskMain.setWorkDocTypeName(danju.getConfigValueName());
        //查询负责人信息
        PsUser user = userDao.getUser(Integer.parseInt(taskManagerId));
        psSolvetaskMain.setTaskManagerId(Integer.parseInt(taskManagerId));
        psSolvetaskMain.setTaskManagerCode(user.getName());
        psSolvetaskMain.setTaskManagerName(user.getUsername());
        //修改信息
        solveMainDao.update(psSolvetaskMain);
        if(!solverStr.equals("")){
            //添加消缺员任务
            solverDao.updateSolverTask(solverIds,psSolvetaskMain.getId());
        }
        map.put("result",true);
        return map;
    }

    @RequestMapping("/solverSelectIndex")
    public String solverSelectIndex() throws Exception{
        return "system/solverSelect/index";
    }

    @RequestMapping("/solverSelect")
    @ResponseBody
    public Map<String, Object> solverSelect(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer limit, PsSolvetaskMain condition, HttpServletRequest request) throws Exception {

        Map<String, Object> map = new HashMap<>();

        Page<PsInspectiontask_main> pager = PageHelper.startPage(page, limit);
        List<PsSolvetaskMain> list = solveMainDao.solverSelect(condition);
        request.setAttribute("list",list);
        map.put("code", 0);
        map.put("msg", "");
        map.put("data", list);
        map.put("count", pager.getTotal());
        return map;
    }
}
